﻿using Hu.Core.Domains.Basic.Interface;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    private readonly DbContext _context;
    private readonly DbSet<TEntity> _dbSet;

    public Repository(DbContext context)
    {
        _context = context;
        _dbSet = _context.Set<TEntity>();
    }
    /*
     ToListAsync 结果集不要太大
     */
    public async Task<IEnumerable<TEntity>> SqlQuery(FormattableString str)
    {
        return await this._context.Database.SqlQuery<TEntity>(str).ToListAsync();
    }
    /// <summary>
    /// 分页查询，待完善
    /// </summary>
    /// <param name="predicate">查询条件</param>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public async Task<IEnumerable<TEntity>> GetDataResponse(Expression<Func<TEntity, bool>> predicate, int pageIndex, int pageSize = 15)
    {
        IQueryable<TEntity> query = this._dbSet.Where(predicate);
        long count = query.LongCount();
        long pageCount = (long)Math.Ceiling(count * 1.0 / pageSize);
        return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
    }

    public async Task<TEntity> GetByIdAsync(int id)
    {
        return await _dbSet.FindAsync(id);
    }

    public async Task<IEnumerable<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> predicate)
    {
        return await _dbSet.Where(predicate).ToListAsync();
    }

    public async Task AddAsync(TEntity entity)
    {
        await _dbSet.AddAsync(entity);
        //await this.SaveChangesAsync();
    }
    public void UpdateAsync(TEntity entity)
    {
        _dbSet.Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
        //await _context.SaveChangesAsync();
    }
    public async Task<int> SaveChangesAsync()
    {
        return await _context.SaveChangesAsync();
    }

    public async Task DeleteAsync(int id)
    {
        var entity = await _dbSet.FindAsync(id);
        if (entity != null)
        {
            _dbSet.Remove(entity);
            await this.SaveChangesAsync();
        }
    }
}